<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>事件通用的监听</title>
  </head>
  <body>
    <div id="dad">
      <a href="">1</a>
      <a href="">2</a>
      <a href="">3</a>
      <a href="">4</a>
      <button>5</button>
    </div>
    <script>
      function bindEvent(dom, event, selector, cb) {
        if (cb == null) {
          cb = selector
          selector = null
        }
        if (dom) {
          dom.addEventListener(event, (e) => {
            let target
            if (selector) {
              // 代理事件
              target = e.target
              if (target.matches(selector)) {
                cb.call(target, e)
              }
            } else {
              // 不需要代理
              cb(e);
            }
          })
        }
      }
      const div = document.querySelector('div#dad')
      bindEvent(div, 'click', 'button', function (event) {
        alert(this.innerHTML)
      })
    </script>
  </body>
</html>
